<?php

namespace app\api\middleware;

use think\Request;
use app\service\WechatMiniProgramService;

class WechatAuth
{
    public function handle(Request $request, \Closure $next)
    {
        $token = $request->header('Api-Token') ?? $request->param('token');

        if (empty($token)) {
            return json(['code' => 401, 'msg' => '请先登录', 'data' => []]);
        }

        $service = new WechatMiniProgramService();
        $payload = $service->verifyToken($token);

        if (!$payload) {
            return json(['code' => 401, 'msg' => '登录已过期，请重新登录', 'data' => []]);
        }

        // 将用户信息添加到请求中
        $request->userInfo = $payload;
        $request->userId = $payload['user_id'];

        return $next($request);
    }
}